package com.mrent.web.controller.common;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.mrent.entity.Picture;
import com.mrent.service.PictureService;


@Controller
public class PictureController {
	
	@Autowired
	private PictureService pictureService;
	
	/**
	 * 图片显示.
	 * 
	 * @param pictureId
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/picture/show/{pictureId}")
	public String showPicture(@PathVariable Long pictureId,Integer w,Integer h,HttpServletResponse response) throws IOException{
		Picture picture = pictureService.getPicture(pictureId);
        if(picture != null){
        	Blob b = picture.getPictureData();
        	byte[] imgData = b.getBytes();
        	if(w == null && h == null){
        		imgData = b.getBytes();
        	}else{
        		ImagesService imagesService = ImagesServiceFactory.getImagesService();
                Image oldImage = ImagesServiceFactory.makeImage(imgData);
                Transform resize = ImagesServiceFactory.makeResize(w, h);
                Image newImage = imagesService.applyTransform(resize, oldImage);
                imgData = newImage.getImageData();
                
        	}
        	response.setContentType("image/jpeg;charset=utf-8");
            response.getOutputStream().write(imgData);
            response.getOutputStream().close();
        	
        	
            
        }
        return null;
	}

}
